package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.IRabbitMQService;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {
    @Resource
    private RedisIdWorker redisIdWorker;
    @Resource
    private ISeckillVoucherService seckillVoucherService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private IRabbitMQService rabbitMQService;
    private IVoucherOrderService proxy;
    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    //异步处理线程池
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();
    
    // 标记是否应该继续运行
    private volatile boolean shouldRun = true;
    
    // 性能统计
    private AtomicLong processedOrders = new AtomicLong(0);
    private volatile long lastPrintTime = System.currentTimeMillis();

    //在类初始化之后执行，因为当这个类初始化好了之后，随时都是有可能要执行的
    @PostConstruct
    private void init() {
        // 初始化流和消费者组
        initStreamAndGroup();
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }
    
    // 在容器关闭前执行，用于优雅关闭线程池
    @PreDestroy
    public void destroy() {
        shouldRun = false;
        SECKILL_ORDER_EXECUTOR.shutdown();
        System.out.println("总共处理订单数: " + processedOrders.get());
    }

    // 初始化流和消费者组
    private void initStreamAndGroup() {
        try {
            // 先检查流是否存在
            stringRedisTemplate.opsForStream().createGroup("stream.orders", "g1");
        } catch (Exception e) {
            // 如果流或消费者组已存在，则忽略异常
            System.out.println("流或消费者组可能已存在，无需重复创建: " + e.getMessage());
        }
    }

    // 用于线程池处理的任务
    private class VoucherOrderHandler implements Runnable {

        @Override
        public void run() {
            while (shouldRun) {
                try {
                    // 1.获取消息队列中的订单信息 XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS s1 >
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create("stream.orders", ReadOffset.lastConsumed())
                    );
                    // 2.判断订单信息是否为空
                    if (list == null || list.isEmpty()) {
                        // 如果为null，说明没有消息，继续下一次循环
                        continue;
                    }
                    // 解析数据
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    // 3.创建订单
                    createVoucherOrder(voucherOrder);
                    // 4.确认消息 XACK
                    stringRedisTemplate.opsForStream().acknowledge("stream.orders", "g1", record.getId());
                    
                    // 性能统计
                    long count = processedOrders.incrementAndGet();
                    long currentTime = System.currentTimeMillis();
                    if (currentTime - lastPrintTime > 5000) { // 每5秒打印一次
                        System.out.println("已处理订单数: " + count);
                        lastPrintTime = currentTime;
                    }
                } catch (Exception e) {
                    log.error("处理订单异常", e);
                    if (shouldRun) {
                        //处理异常消息
                        handlePendingList();
                    }
                }
            }
        }

        private void handlePendingList() {
            while (shouldRun) {
                try {
                    // 1.获取pending-list中的订单信息 XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS s1 0
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1),
                            StreamOffset.create("stream.orders", ReadOffset.from("0"))
                    );
                    // 2.判断订单信息是否为空
                    if (list == null || list.isEmpty()) {
                        // 如果为null，说明没有异常消息，结束循环
                        break;
                    }
                    // 解析数据
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    // 3.创建订单
                    createVoucherOrder(voucherOrder);
                    // 4.确认消息 XACK
                    stringRedisTemplate.opsForStream().acknowledge("stream.orders", "g1", record.getId());
                } catch (Exception ex) {
                    log.error("处理pendding订单异常", ex);
                    if (!shouldRun) {
                        break;
                    }
                    try{
                        Thread.sleep(20);
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    private void checkAndLoadSeckillVoucherToCache(Long voucherId) {
        String stockKey = RedisConstants.SECKILL_STOCK_KEY + voucherId;
        // 从Redis中获取库存信息
        String json = stringRedisTemplate.opsForValue().get(stockKey);
        
        // 如果Redis中没有库存信息，则从数据库加载
        if (json == null) {
            loadSeckillVoucherToCache(voucherId);
            return;
        }
        
        // 检查逻辑过期时间
        try {
            JSONObject jsonObject = JSONUtil.parseObj(json);
            if (jsonObject.containsKey("expireTime") && jsonObject.containsKey("data")) {
                // 新格式，包含逻辑过期时间
                String expireTimeStr = jsonObject.getStr("expireTime");
                LocalDateTime expireTime = LocalDateTime.parse(expireTimeStr.replace("\"", ""));
                // 判断是否过期
                if(expireTime.isAfter(LocalDateTime.now())) {
                    // 未过期，直接返回
                    return;
                }
            } else {
                // 旧格式，没有逻辑过期时间，直接使用
                return;
            }
        } catch (Exception e) {
            // 解析失败，当作没有缓存处理
        }
        
        // 已过期或解析失败，需要重建缓存
        loadSeckillVoucherToCache(voucherId);
    }
    
    private void loadSeckillVoucherToCache(Long voucherId) {
        String stockKey = RedisConstants.SECKILL_STOCK_KEY + voucherId;
        // 查询数据库中的秒杀券信息
        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
        
        // 如果数据库中存在该秒杀券，则将库存信息存入Redis
        if (seckillVoucher != null && seckillVoucher.getStock() > 0) {
            // 为了兼容Lua脚本，我们存储两种格式的缓存：
            // 1. 如果是首次加载或缓存已过期，存储为纯数字格式，用于秒杀操作
            stringRedisTemplate.opsForValue().set(stockKey, seckillVoucher.getStock().toString());
            
            // 2. 同时设置订单集合的key，确保Lua脚本正常运行
            String orderKey = "seckill:order:" + voucherId;
            stringRedisTemplate.opsForSet().add(orderKey, "init"); // 添加一个初始值，确保key存在
            stringRedisTemplate.opsForSet().remove(orderKey, "init"); // 立即移除初始值
            
            // 3. 设置一个带有逻辑过期时间的备份键，用于定期检查
            RedisData redisData = new RedisData();
            redisData.setData(seckillVoucher.getStock().toString());
            redisData.setExpireTime(LocalDateTime.now().plusSeconds(30));
            String backupKey = stockKey + ":backup";
            stringRedisTemplate.opsForValue().set(backupKey, JSONUtil.toJsonStr(redisData));
        }
    }

    @Override
    public Result seckillVoucher(Long voucherId) {
        // 检查并加载秒杀券信息到缓存
        checkAndLoadSeckillVoucherToCache(voucherId);
        
        Long userId = UserHolder.getUser().getId();
        long orderId = redisIdWorker.nextId("order");
        // 1.执行lua脚本
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString(), String.valueOf(orderId)
        );
        int r = result.intValue();
        // 2.判断结果是否为0
        if (r != 0) {
            // 2.1.不为0 ，代表没有购买资格
            return Result.fail(r == 1 ? "库存不足" : "不能重复下单");
        }
        // 3.发送消息到RabbitMQ
        rabbitMQService.sendVoucherMessage(String.valueOf(orderId));
        // 4.直接返回订单id，订单将通过RabbitMQ异步处理
        return Result.ok(orderId);
    }

    @Override
    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        Long userId = voucherOrder.getUserId();
        Long voucherId = voucherOrder.getVoucherId();
        // 5.1.查询订单
        int count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
        // 5.2.判断是否存在
        if (count > 0) {
            // 用户已经购买过了
            System.err.println("用户已经购买过了");
            return;
        }
        // 6.扣减库存
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock - 1") // set stock = stock - 1
                .eq("voucher_id", voucherId).gt("stock", 0) // where id = ? and stock > 0
                .update();
        if (!success) {
            // 扣减失败
            System.err.println("库存不足");
            return;
        }
        save(voucherOrder);
    }
    
    // 获取处理的订单数用于测试
    public long getProcessedOrders() {
        return processedOrders.get();
    }
    
    // 重置计数器
    public void resetProcessedOrders() {
        processedOrders.set(0);
    }
}